
#include <assert.h>
#include <string.h>


#include "OSMutex.h"


// Private globals
#if __PTHREADS_MUTEXES__
static pthread_mutexattr_t  *sMutexAttr = NULL;
static void MutexAttrInit();

#if __solaris__
static pthread_once_t sMutexAttrInit = { PTHREAD_ONCE_INIT };
#else
static pthread_once_t sMutexAttrInit = PTHREAD_ONCE_INIT;
#endif

#endif
OSMutex::OSMutex()
{
#ifdef WIN32
    ::InitializeCriticalSection(&fMutex);
    fHolder = 0;
    fHolderCount = 0;
#elif __PTHREADS_MUTEXES__
    (void)pthread_once(&sMutexAttrInit, MutexAttrInit);
    (void)pthread_mutex_init(&fMutex, sMutexAttr);

    fHolder = 0;
    fHolderCount = 0;
#else
    fMutex = mymutex_alloc();
#endif
}

#if __PTHREADS_MUTEXES__
void MutexAttrInit()
{
    sMutexAttr = (pthread_mutexattr_t*)malloc(sizeof(pthread_mutexattr_t));
    ::memset(sMutexAttr, 0, sizeof(pthread_mutexattr_t));
    pthread_mutexattr_init(sMutexAttr);
}
#endif

OSMutex::~OSMutex()
{
#ifdef WIN32
    ::DeleteCriticalSection(&fMutex);
#elif __PTHREADS_MUTEXES__
    pthread_mutex_destroy(&fMutex);
#else
    mymutex_free(fMutex);
#endif
}





#if __PTHREADS_MUTEXES__ || WIN32
void OSMutex::RecursiveLock()
{
    // We already have this mutex. Just refcount and return
    if (OSThread::GetCurrentThreadID() == fHolder)
    {
        fHolderCount++;
		//printf("fHolderCount = %d\n", fHolderCount);
        return;
    }
#ifdef WIN32
    ::EnterCriticalSection(&fMutex);
#else
    (void)pthread_mutex_lock(&fMutex);
#endif
    assert(fHolder == 0);
    fHolder = OSThread::GetCurrentThreadID();
    fHolderCount++;
    assert(fHolderCount == 1);
}

void OSMutex::RecursiveUnlock()
{
    if (OSThread::GetCurrentThreadID() != fHolder)
        return;

    assert(fHolderCount > 0);
    fHolderCount--;
    if (fHolderCount == 0)
    {
	//	printf("fHolderCount = %d\n", fHolderCount);
        fHolder = 0;
#ifdef WIN32
        ::LeaveCriticalSection(&fMutex);
#else
        pthread_mutex_unlock(&fMutex);
#endif
    }
}

Bool16      OSMutex::RecursiveTryLock()
{
    // We already have this mutex. Just refcount and return
    if (OSThread::GetCurrentThreadID() == fHolder)
    {
        fHolderCount++;
        return true;
    }

#ifdef WIN32
    Bool16 theErr = (Bool16)::TryEnterCriticalSection(&fMutex); // Return values of this function match our API
    if (!theErr)
        return theErr;
#else
    int theErr = pthread_mutex_trylock(&fMutex);
    if (theErr != 0)
    {
        assert(theErr == EBUSY);
        return false;
    }
#endif
    assert(fHolder == 0);
    fHolder = OSThread::GetCurrentThreadID();
    fHolderCount++;
    assert(fHolderCount == 1);
    return true;
}
#endif //__PTHREADS_MUTEXES__ || __Win32__
